package cn.time1024.time_app.ui.home

import android.os.Bundle
import android.widget.Toast
import android.app.AlertDialog
import android.widget.EditText
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.time1024.time_app.R
import cn.time1024.time_app.data.api.WorkflowApiClient
import cn.time1024.time_app.databinding.FragmentWorkflowBinding

/**
 * 工作流页面：用于展示工作流相关内容的占位页面。
 */
/**
 * 工作流页面：展示工作流列表并支持新增、更新、删除与运行。
 */
class WorkflowFragment : Fragment() {
    private var _binding: FragmentWorkflowBinding? = null
    private val binding get() = _binding!!

    private lateinit var api: WorkflowApiClient
    private val items = mutableListOf<WorkflowApiClient.WorkflowDto>()

    /**
     * 创建并返回工作流视图。
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentWorkflowBinding.inflate(inflater, container, false)
        return binding.root
    }

    /**
     * 视图创建后初始化列表、API 客户端与交互事件。
     * - 设置 RecyclerView、Adapter 与点击事件。
     * - 绑定新增按钮。
     * - 设置下拉刷新与首次数据加载。
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 基础URL来自strings.xml，可按需修改为后端地址
        val baseUrl = getString(R.string.api_base_url)
        api = WorkflowApiClient(baseUrl)

        binding.recyclerWorkflows.layoutManager = LinearLayoutManager(requireContext())
        val adapter = object : RecyclerView.Adapter<VH>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
                val v = layoutInflater.inflate(R.layout.item_workflow, parent, false)
                return VH(v)
            }
            override fun getItemCount(): Int = items.size
            override fun onBindViewHolder(holder: VH, position: Int) {
                val item = items[position]
                holder.bind(item)
                holder.btnRun.setOnClickListener { runWorkflow(item) }
                holder.btnMore.setOnClickListener { showMoreMenu(item) }
                holder.itemView.setOnClickListener { showEditDialog(item) }
            }
        }
        binding.recyclerWorkflows.adapter = adapter

        binding.fabAddWorkflow.setOnClickListener {
            showAddDialog()
        }

        // 设置下拉刷新
        setupSwipeRefresh()
        // 首次加载放到子线程，避免主线程网络调用导致空列表
        Thread { loadData() }.start()
    }

    /**
     * 加载工作流数据并刷新列表。
     * - 后台线程拉取数据，主线程刷新 UI。
     * - 同步更新底部总数文本与刷新状态。
     */
    private fun loadData() {
        val list = api.fetchAll()
        requireActivity().runOnUiThread {
            items.clear()
            items.addAll(list)
            binding.recyclerWorkflows.adapter?.notifyDataSetChanged()
            if (list.isEmpty()) {
                Toast.makeText(requireContext(), "暂无工作流或网络不可用", Toast.LENGTH_SHORT).show()
            }
            updateTotalText()
            binding.swipeRefreshWorkflows.isRefreshing = false
        }
    }

    /**
     * 显示新增工作流对话框，并在子线程调用后端创建接口。
     */
    private fun showAddDialog() {
        val etName = EditText(requireContext()).apply { hint = "工作流名称" }
        val etDesc = EditText(requireContext()).apply { hint = "描述(可选)" }
        val etContent = EditText(requireContext()).apply { hint = "内容JSON(可选)" }

        val containerParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 24, 32, 0)
            addView(etName, containerParams)
            addView(etDesc, containerParams)
            addView(etContent, containerParams)
        }

        AlertDialog.Builder(requireContext())
            .setTitle("新增工作流")
            .setView(wrapper)
            .setPositiveButton("确定") { _, _ ->
                val name = etName.text?.toString()?.trim().orEmpty()
                val desc = etDesc.text?.toString()?.trim()
                val content = etContent.text?.toString()?.trim()
                if (name.isEmpty()) {
                    Toast.makeText(requireContext(), "名称不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                Thread {
                    val created = api.create(name, desc, content)
                    requireActivity().runOnUiThread {
                        if (created != null) {
                            Toast.makeText(requireContext(), "添加成功", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(requireContext(), "添加失败，请检查网络或后端", Toast.LENGTH_SHORT).show()
                        }
                    }
                    loadData()
                }.start()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 显示编辑工作流对话框，并提交更新。
     * - 预填现有名称、描述与内容，支持修改。
     */
    private fun showEditDialog(item: WorkflowApiClient.WorkflowDto) {
        val etName = EditText(requireContext()).apply { hint = "工作流名称"; setText(item.name ?: "") }
        val etDesc = EditText(requireContext()).apply { hint = "描述(可选)"; setText(item.description ?: "") }
        val etContent = EditText(requireContext()).apply { hint = "内容JSON(可选)"; setText(item.content ?: "") }

        val containerParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 24, 32, 0)
            addView(etName, containerParams)
            addView(etDesc, containerParams)
            addView(etContent, containerParams)
        }

        AlertDialog.Builder(requireContext())
            .setTitle("编辑工作流")
            .setView(wrapper)
            .setPositiveButton("保存") { _, _ ->
                val name = etName.text?.toString()?.trim()
                val desc = etDesc.text?.toString()?.trim()
                val content = etContent.text?.toString()?.trim()
                if (name.isNullOrEmpty()) {
                    Toast.makeText(requireContext(), "名称不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                Thread {
                    val updated = api.update(item.id, name, desc, content)
                    requireActivity().runOnUiThread {
                        Toast.makeText(requireContext(), if (updated != null) "更新成功" else "更新失败", Toast.LENGTH_SHORT).show()
                    }
                    loadData()
                }.start()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 展示更多菜单（编辑 / 删除）。
     * - 删除带确认提示，执行后刷新。
     */
    private fun showMoreMenu(item: WorkflowApiClient.WorkflowDto) {
        val options = arrayOf("编辑", "删除")
        AlertDialog.Builder(requireContext())
            .setTitle(item.name ?: "工作流")
            .setItems(options) { dialog, which ->
                when (which) {
                    0 -> showEditDialog(item)
                    1 -> confirmDelete(item)
                }
                dialog.dismiss()
            }
            .show()
    }

    /**
     * 确认并删除工作流。
     * - 后台线程调用删除接口，主线程提示与刷新。
     */
    private fun confirmDelete(item: WorkflowApiClient.WorkflowDto) {
        AlertDialog.Builder(requireContext())
            .setTitle("删除确认")
            .setMessage("确认删除【${item.name ?: "未命名"}】？")
            .setPositiveButton("删除") { _, _ ->
                Thread {
                    val ok = api.delete(item.id)
                    requireActivity().runOnUiThread {
                        Toast.makeText(requireContext(), if (ok) "删除成功" else "删除失败", Toast.LENGTH_SHORT).show()
                    }
                    loadData()
                }.start()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 运行工作流并提示结果。
     * - 后台线程执行，主线程展示成功/失败消息。
     */
    private fun runWorkflow(item: WorkflowApiClient.WorkflowDto) {
        Thread {
            val result = api.run(item.id)
            requireActivity().runOnUiThread {
                if (result != null && result.success) {
                    Toast.makeText(requireContext(), "运行成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(requireContext(), "运行失败", Toast.LENGTH_SHORT).show()
                }
            }
            loadData()
        }.start()
    }

    /**
     * 设置下拉刷新监听。
     * - 下拉时重新加载列表。
     */
    private fun setupSwipeRefresh() {
        binding.swipeRefreshWorkflows.setOnRefreshListener {
            Thread { loadData() }.start()
        }
    }

    /**
     * 更新底部总数显示。
     * - 文案：共 X 条工作流。
     */
    private fun updateTotalText() {
        binding.tvTotalWorkflows.text = "共 ${items.size} 条工作流"
    }

    /**
     * ViewHolder 表示单项视图绑定器。
     */
    private class VH(v: View) : RecyclerView.ViewHolder(v) {
        val btnRun: View = v.findViewById(R.id.btnRun)
        val btnMore: View = v.findViewById(R.id.btnMore)
        private val txtName = v.findViewById<android.widget.TextView>(R.id.txtName)
        private val txtDesc = v.findViewById<android.widget.TextView>(R.id.txtDesc)

        /** 绑定数据到视图 */
        fun bind(item: WorkflowApiClient.WorkflowDto) {
            txtName.text = item.name ?: "未命名"
            txtDesc.text = item.description ?: ""
        }
    }

    /**
     * 销毁视图时释放绑定。
     */
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}